class ResLoader {

    //加载bundle
    public async loadBundle(bundleUrl: string): Promise<cc.AssetManager.Bundle> {
        return new Promise((resolve, reject) => {
            cc.assetManager.loadBundle(bundleUrl, (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    throw new Error("loadBundle[" + bundleUrl + "] 无效bundle")
                }

                resolve(bundle)
            })
        })
    }


    //加载资源
    public async load(assetUrl: string, type: typeof cc.Asset, bundleKey?: string):Promise<any> {
        let bundle = bundleKey ? cc.assetManager.getBundle(bundleKey) : cc.assetManager.resources

        if (!bundle) {
            //cc.resources 是内置的 必然有 所以默认是 加载 bundle
            bundle = await this.loadBundle(bundleKey).catch(error => {
                throw new Error(error)
            })
        }

        return new Promise<cc.Asset | cc.Node>((resolve, reject) => {
            let onComplete = (err: Error, asset: any) => {
                if (err) {
                    throw new Error("LoadAsset[" + assetUrl + "] Asset错误")
                }
      
                resolve(asset)
            }

            if (assetUrl.startsWith("http")) {
                cc.assetManager.loadRemote(assetUrl, onComplete);
            } else {
                bundle.load(assetUrl, type, onComplete);
            }
        });
    }

    /** 计算当前纹理数量和缓存 */
    public computeTextureCache() {
        return `缓存 [资源总数:${cc.assetManager.assets.count}]`;
    }
}

export default new ResLoader()
